package leetcode_题库;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/23 10:53 星期二
 */
public class _116_填充每个节点的下一个右侧节点指针 {
    public static void main(String[] args) {

    }

    public Node connect(Node root) {
        //所有结点的next都默认指向null，所以根结点不需要管
        if (root == null){
            //若结点为null，则返回空
            return null;
        }
        if (root.left != null){
            //若结点的左结点不为null，让左结点的next指向右结点
            root.left.next = root.right;
        }
        if (root.right != null && root.next != null){
            //若结点右子结点不为null且结点的下一层序结点不为null，让结点的右结点对应next指向结点的下一结点的左结点
            root.right.next = root.next.left;
        }
        root.left = connect(root.left);
        root.right = connect(root.right);

        return root;
        /*

            > 2022/08/23 14:06:49
            解答成功:
                执行耗时:0 ms,击败了100.00% 的Java用户
                内存消耗:41.4 MB,击败了82.17% 的Java用户

         */
    }

    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;
        public Node() {}

        public Node(int _val) {
            val = _val;
        }
        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
